package com.mmall.service;

import com.google.common.base.Preconditions;
import com.mmall.beans.PageQuery;
import com.mmall.beans.PageResult;
import com.mmall.common.RequestHolder;
import com.mmall.dao.SysUserMapper;
import com.mmall.exception.ParamException;
import com.mmall.model.SysUser;
import com.mmall.param.UserParam;
import com.mmall.util.BeanValidator;
import com.mmall.util.IpUtil;
import com.mmall.util.MD5Util;
import com.mmall.util.PasswordUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @Auther 19135
 * @Date 2019/3/24 19:37
 * @Description ${end}$
 */
@Service
public class SysUserService {

	@Resource
	private SysUserMapper sysUserMapper;

	//判断该手机号是否已经被使用
	public boolean checkTelephoneExist(String telephone, Integer userId) {
		return sysUserMapper.countByTelephone(telephone, userId) > 0;
	}

	public boolean checkEmailExist(String mail, Integer userId) {
		return sysUserMapper.countByMail(mail, userId) > 0;
	}


	public void save(UserParam param){
		BeanValidator.check(param);
		if (checkTelephoneExist(param.getTelephone(),param.getId())){
			throw new ParamException("电话已被占用");
		}
		if(checkEmailExist(param.getMail(), param.getId())) {
			throw new ParamException("邮箱已被占用");
		}
		String password = PasswordUtil.randomPassword();
		//TODO
		//暂时默认生成为12345678
		password = "12345678";

		//md5加密
		String encryptedPassword = MD5Util.encrypt(password);
		SysUser user = SysUser.builder().username(param.getUsername()).telephone(param.getTelephone()).mail(param.getMail())
				.password(encryptedPassword).deptId(param.getDeptId()).status(param.getStatus()).remark(param.getRemark()).build();
		user.setOperator(RequestHolder.getCurrentUser().getUsername());
		user.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
		user.setOperateTime(new Date());

		//TODO: sendEmail

		sysUserMapper.insertSelective(user);
		//TODO log

	}

	public void update(UserParam param) {
		BeanValidator.check(param);
		if(checkTelephoneExist(param.getTelephone(), param.getId())) {
			throw new ParamException("电话已被占用");
		}
		if(checkEmailExist(param.getMail(), param.getId())) {
			throw new ParamException("邮箱已被占用");
		}
		SysUser before = sysUserMapper.selectByPrimaryKey(param.getId());
		Preconditions.checkNotNull(before, "待更新的用户不存在");
		SysUser after = SysUser.builder().id(param.getId()).username(param.getUsername()).telephone(param.getTelephone()).mail(param.getMail())
				.deptId(param.getDeptId()).status(param.getStatus()).remark(param.getRemark()).build();
		after.setOperator(RequestHolder.getCurrentUser().getUsername());
		after.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
		after.setOperateTime(new Date());
		sysUserMapper.updateByPrimaryKeySelective(after);

		//TODO log

	}

	//根据key（手机号或则邮箱） 查询user
	public SysUser findByKeyword(String keyword) {
		return sysUserMapper.findByKeyword(keyword);
	}

	public PageResult<SysUser> getPageByDeptId(int deptId, PageQuery page) {
		BeanValidator.check(page);
		int count = sysUserMapper.countByDeptId(deptId);
		if (count > 0) {
			List<SysUser> list = sysUserMapper.getPageByDeptId(deptId, page);
			return PageResult.<SysUser>builder().total(count).data(list).build();
		}
		return PageResult.<SysUser>builder().build();
	}

	public List<SysUser> getAll() {
		return sysUserMapper.getAll();
	}
}
